let intervals = {};
let startTimes = {};
let nowType;
let wasteTime = 0;

async function refresh() {
  const res = await window.electronAPI.refresh();
  document.querySelector(`#todayWork`).innerText = res?.work ?? "快干活！";
  document.querySelector(`#todayHobby`).innerText = res?.hobby ?? "快干活！";
  return res;
}

async function initTargets() {
  const duration = await refresh();
  const config = await window.electronAPI["db-query"](
    "SELECT * FROM config LIMIT 1"
  );
  document.querySelector("#work-minutes").value = config[0].work_target;
  document.querySelector("#hobby-minutes").value = config[0].leisure_target;
  const workPlan =
    config[0].work_target * 60 - Math.round((duration?.workValue ?? 0) * 0.001);

  updateDisplay("work", workPlan);
  document.querySelector("#work-timer-value").innerText = workPlan;
  const hobbyPlan =
    config[0].leisure_target * 60  - Math.round((duration?.hobbyValue ?? 0) * 0.001);
  updateDisplay("hobby", hobbyPlan);
  document.querySelector("#hobby-timer-value").innerText = hobbyPlan;
}

initTargets();

function updateDisplay(type, remaining) {
  const timerElement = document.getElementById(`${type}-timer`);
  document.querySelector(`#${type}-timer-value`).innerText = remaining;
  if (remaining <= 0) {
    timerElement.textContent =
      "已超期：" +
      `${Math.floor(-remaining / 60)
        .toString()
        .padStart(2, "0")}:` +
      `${(-remaining % 60).toString().padStart(2, "0")}`;
  } else {
    timerElement.textContent =
      `${Math.floor(remaining / 60)
        .toString()
        .padStart(2, "0")}:` +
      `${(remaining % 60).toString().padStart(2, "0")}`;
  }
  timerElement.classList.toggle("red", remaining <= 0);
}

function startTimer(type, plus) {
  if (nowType == type) return;
  // 停止所有计时器
  stopAllTimers();

  nowType = type;

  // 记录开始时间
  const startTime = Date.now();
  window.electronAPI.recordStart(type, startTime);
  startTimes[type] = startTime;
  let remaining = document.querySelector(`#${type}-timer-value`).innerText;

  intervals[type] = setInterval(() => {
    remaining--;
    wasteTime++;
    if (wasteTime % 60 == 0) {
      console.log("又过了1分钟，我要存盘了！");
      const sql = `update records set duration = "${wasteTime * 1000}" , end_time="${Date.now()}" where type = "${type}" and start_time = "${
        startTimes[type]
      }"`;

      window.electronAPI["db-query"](sql);
    }
    updateDisplay(type, remaining);
  }, 1000);
}

function plusTimer(type, plus) {
  if (plus) {
    let remaining = document.querySelector(`#${type}-timer-value`).innerText;

    remaining = parseInt(remaining);
    remaining += plus;
    document.querySelector(`#${type}-timer-value`).innerText = remaining;
    document.getElementById(`${type}-timer`).textContent =
      `${Math.floor(remaining / 60)
        .toString()
        .padStart(2, "0")}:` +
      `${(remaining % 60).toString().padStart(2, "0")}`;

    if (type == nowType) {
      clearInterval(intervals[type]);
      intervals[type] = setInterval(() => {
        remaining--;
        updateDisplay(type, remaining);
      }, 1000);
    }
  }
}

function stopAllTimers() {
  Object.keys(intervals).forEach((type) => {
    clearInterval(intervals[type]);
    if (startTimes[type]) {
      const duration = Date.now() - new Date(startTimes[type]).getTime();

      window.electronAPI.recordStop(
        type,
        startTimes[type],
        duration,
        Date.now()
      );
      delete startTimes[type];
      wasteTime = 0;
    }
  });
  nowType = "";
  intervals = {};
  startTimes = {};
}
